from rest_framework.views import APIView
from rest_framework.response import Response
from .models import NoticeMembersModel,NoticeModel
from .serializers import NoticeSerializer
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from django.http import QueryDict

class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return

class NoticeView(APIView):
    authentication_classes = (CsrfExemptSessionAuthentication, BasicAuthentication)
    
    def get(self, request):
        context = dict()
        context['err_code'] = 0
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        notices = NoticeMembersModel.objects.filter(done=False,user=user)
        notices = NoticeSerializer(notices,many=True)
        context['data'] = notices.data
        return Response(context)
    def put(self,request):
        context = dict()
        context['err_code'] = 0
        user = request.user
        if user.is_anonymous:
            context['err_code'] = 1001
            context['error'] = "您还未登录"
            return Response(context)
        id =  QueryDict(request.body).get('id')
        if id is None:
            context['err_code'] = 2002
            context['error'] = "参数错误"
            return Response(context)
        try:
            id = int(id)
        except:
            context['err_code'] = 2002
            context['error'] = "参数错误"
            return Response(context)

        notice = NoticeMembersModel.objects.filter(id=id)
        if not notice.exists():
            context['err_code'] = 4003
            context['error'] = "您没有收到此通知"
            return Response(context)
        done = notice.first()
        if done.user != user:
            context['err_code'] = 4003
            context['error'] = "此通知不属于您"
            return Response(context)
        done.done = True
        done.save()
        return Response(context)

